package com.ruoyi.web.controller.wxqy.activities;

import com.ruoyi.common.annotation.ControllerAuthority;
import com.ruoyi.common.constant.ErrorConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.qywx.entity.Survey;
import com.ruoyi.qywx.model.vo.ServeyQuestionVo;
import com.ruoyi.qywx.service.inters.SurveyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author : hcl
 * @Date : 2023/9/14 10:11
 */
@RestController
@RequestMapping("/wxqy/activity/survey")
@ControllerAuthority
public class SurveyController extends BaseController {
    @Autowired
    private SurveyService surveyService;

    @GetMapping("/list")
    public AjaxResult list(String keyword) {
        startPage();
        return success(getDataTable(surveyService.list(keyword, getTeamId())));
    }

    @GetMapping("/detail")
    public AjaxResult detail(Long id) {
        if (NumberUtils.isFalse(id)) {
            return error(ErrorConstants.PARAMS_ERR);
        }
        Survey survey = surveyService.selectSurveyById(id, getTeamId());
        if (survey == null) {
            return error(ErrorConstants.NO_DATA);
        }
        return success(survey);
    }

    @PostMapping("/edit")
    public AjaxResult edit(
            @RequestParam(name = "id", required = false) Long id,
            @RequestParam(name = "startTime") String startTime,
            @RequestParam(name = "endTime") String endTime,
            @RequestBody List<ServeyQuestionVo> questions) {
        if (StrUtils.isEmpty(startTime) || StrUtils.isEmpty(endTime)) {
            return error("请检查问卷开始/结束时间是否设置正确");
        }
        if (CollectionUtils.isEmpty(questions)) {
            return error(ErrorConstants.PARAMS_ERR);
        }
        Date start = DateUtils.dateTime(startTime), end = DateUtils.dateTime(endTime);
        if (!DateUtils.gt(end, start)) {
            return error("请正确设置问卷开始/结束时间");
        }
        return NumberUtils.isFalse(id)
                ? surveyService.create(questions, getUserId(), start, end, getTeamId())
                : surveyService.edit(id, start, end, questions, getTeamId());
    }

    public static void main(String[] args) {
        Date start = DateUtils.dateTime("2023-09-14 16:59:25"), end = DateUtils.dateTime("2023-09-14 16:59:25");
        if (DateUtils.gt(end, start)) {
            System.out.println("请正确设置问卷开始/结束时间");
        }
    }
}
